import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login'
import Home from '../components/Home'
import Welcome from '../components/Welcome'
import Users from '../components/user/Users'
import Rights from '../components/power/Rights'
import Roles from '../components/power/Roles'

Vue.use(VueRouter)

const routes = [
  {
    path:'/',redirect:'/login'   //设置如果路径为/，则自动跳转到/login路径下
  },
  {
    path:'/login',component:Login
  },
  {
    path:'/home',
    component:Home,
    redirect:'/welcome',  //将/home重定向为/welcome页面
    children:[
      {
        path:'/welcome',component:Welcome   //配置welcome的路由
      },
      {
        path:'/users',component:Users  // 配置子级菜单路由
      },
      {
        path:'/rights',component:Rights  // 配置子级菜单路由
      },
      {
        path:'/roles',component:Roles  // 配置子级菜单路由
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

//挂载路由导航守卫，如果没有token,在只能前往login页面
router.beforeEach((to,from,next)=>{
//to 将要访问的路径
//from 代表从哪个路径跳转而来
//next 是一个函数，表示放行
//next()放行 next('/login'),表示强制跳转到login
  if(to.path==='/login')return next();  //如果将要访问loging页面，放行
  //获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if(!tokenStr)return next('/login')    //如果非tokenStr，字符串不存在，强制跳转
  next()   //否则放行
})
export default router
